#include "chatserver.hpp"
#include "json.hpp"
#include "chatservice.hpp"

#include <functional>

using namespace muduo;
using namespace muduo::net;
using namespace std;


ChatServer::ChatServer(muduo::net::EventLoop* loop,
    const muduo::net::InetAddress& listenAddr,
    const std::string& nameArg)
    :server_(loop, listenAddr, nameArg)
    ,loop_(loop)
{
    server_.setConnectionCallback(std::bind(&ChatServer::onConnection, this, std::placeholders::_1));
    server_.setMessageCallback(std::bind(&ChatServer::onMessage, this, std::placeholders::_1, 
        std::placeholders::_2, std::placeholders::_3));
    server_.setThreadNum(4);
}
void ChatServer::start()
{
    server_.start();
}

void ChatServer::onConnection(const muduo::net::TcpConnectionPtr &conn)
{
    if (!conn->connected()) {
        ChatService::instance()->clientCloseExecption(conn);
        conn->shutdown();
    }
}

void ChatServer::onMessage(const muduo::net::TcpConnectionPtr &conn, 
    muduo::net::Buffer *buffer, muduo::Timestamp time)
{
    string buf = buffer->retrieveAllAsString();
    json js = json::parse(buf);

    auto msgHandler = ChatService::instance()->getHangler(js["msgid"].get<int>());
    msgHandler(conn, js, time);
}